package com.gitee.qdbp.jdbc.test.base;

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import com.gitee.qdbp.jdbc.api.QdbcBoot;

@Service
public class DatabaseInitializer extends AbstractTestNGSpringContextTests {

    @Value("#{setting['database.init.enabled']}")
    private boolean enabled;
    @Autowired
    private QdbcBoot qdbcBoot;

    @PostConstruct
    public synchronized void init() {
        // H2内存数据库, 必须初始化, 否则找不到表
        if (enabled || qdbcBoot.sqlDialect().dbVersion().matchesWith("h2")) {
            initTables(qdbcBoot);
        }
    }

    public static void initTables(QdbcBoot qdbcBoot) {
        String dbType = qdbcBoot.sqlDialect().dbVersion().getDbType().name().toLowerCase();
        String path = "settings/dbinit/create.tables." + dbType + ".sql";
        qdbcBoot.sqlJdbc().executeSqlScript(path);
    }
}
